package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;


    //员工登录
    @Override
    public ResultInfo login(String username, String password) {
        //根据username查询mapper
        Employee employee = employeeMapper.findByUsername(username);

        //判断账户是否存在
        if (employee == null) {
            return ResultInfo.error("此用户不存在...");
        }

        //判断密码
        //将前端密码md5加密
        String md5 = SecureUtil.md5(password);
        //比较数据库
        if (!md5.equals(employee.getPassword())) {
            return ResultInfo.error("密码错误...");
        }

        //判断账户是否可用
        if (employee.getStatus() == 0) {
            return ResultInfo.error("此账号被禁用");
        }
        return ResultInfo.success(employee);
    }

    //员工列表
    @Override
    public List<Employee> findList(String name) {
        return employeeMapper.findList(name);
    }

    //员工新增
    @Override
    public void save(Employee employee) {
        //雪花算法生成ID
        long id = IdUtil.getSnowflake(1, 1).nextId();
        //传入生成的id
        employee.setId(id);
        //初始密码
        String md5 = SecureUtil.md5(Constant.INIT_PASSWORD);
        //传入加密后的密码
        employee.setPassword(md5);
        //员工状态
        employee.setStatus(1);
        //创建时间,更改时间
        //employee.setCreateTime(new Date());
        //employee.setUpdateTime(new Date());
        //添加员工的操作人
        //employee.setCreateUser(1L);//TODO
        //employee.setUpdateUser(1L);//TODO

        //调用mapper方法
        employeeMapper.save(employee);
    }

    //员工修改回显
    @Override
    public Employee findById(Long id) {
        return employeeMapper.faindById(id);
    }

    //员工修改
    @Override
    public void update(Employee employee) {
        //补全信息
        //修改人员
        //employee.setUpdateUser(1L);//TODO


        //修改时间
        //employee.setUpdateTime(new Date());
        //调用mapper修改
        //employeeMapper.update(employee);
        //自动填充需要使用官方的方法，否则不会修改
        employeeMapper.updateById(employee);
    }

}
